//
//  WMEFindViewController.m
//  everyDay_duiTang
//
//  Created by 恩叔 on 16/1/18.
//  Copyright © 2016年 enshu. All rights reserved.
//

#import "WMEFindViewController.h"
#import "WMEFindModel.h"
#import "WMETheFindTableViewCell.h"
#import <AFNetworking.h>
#import <Masonry.h>
#import "WMEFindContentViewController.h"
#import "WMEFindHeadCollectionViewCell.h"
#import "WMEShopViewController.h"
#import "WMEFindCollectionViewController.h"
#import "WMEFindSearchViewController.h"
#import "SearchViewController.h"

@interface WMEFindViewController ()<UITableViewDataSource, UITableViewDelegate, findPushActionDelegate, UICollectionViewDataSource,UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)UICollectionView *collectionView;
@property (nonatomic, retain)NSMutableArray *mArr;
@property (nonatomic, retain)NSMutableArray *titleArr;
@property (nonatomic, retain)NSMutableArray *dataArr;
@property (nonatomic, retain)NSMutableArray *collectionArr;
@property (nonatomic, retain)UIView *headView;

@end

@implementation WMEFindViewController
- (void)dealloc
{
    [_tableView release];
    [_collectionView release];
    [_mArr release];
    [_titleArr release];
    [_dataArr release];
    [_collectionArr release];
    [_headView release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    //把navigation隐藏起来
//    self.navigationController.navigationBar.hidden = YES;
    self.navigationItem.title = @"发现";
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"搜索" style:UIBarButtonItemStylePlain target:self action:@selector(searchAction:)];
    [self cjView];
    [self data];
    [self createCollection];
}

- (void)cjView
{
//    //隐藏掉了navigation 自己写一个view 装搜索栏
//    UIView *view = [[UIView alloc] init];
//    view.backgroundColor = [UIColor colorWithRed:244/255.0 green:244/255.0 blue:244/255.0 alpha:1];
//    [self.view addSubview:view];
////    __block WMEFindViewController *find = self;
//    [view mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.size.mas_equalTo(CGSizeMake(300, 64));
//        
//        make.centerX.mas_equalTo(self.view.center);
//        make.top.equalTo(self.view).with.offset(0);
//        make.left.equalTo (self.view).with.offset(0);
//        make.right.equalTo(self.view).with.offset(0);
//    }];
//    //线
//    UILabel *lll = [[UILabel alloc] init];
////    __block WMEFindViewController *find = self;
//    lll.backgroundColor = [UIColor grayColor];
//    [self.view addSubview:lll];
//    [lll mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.size.mas_equalTo(CGSizeMake(300, 0.3));
//        
//        make.centerX.mas_equalTo(self.view.center);
//        make.top.equalTo(self.view).with.offset(64);
//        make.left.equalTo(self.view).with.offset(0);
//        make.right.equalTo(self.view).with.offset(0);
//    }];
//    //标题label
//    UILabel *label = [[UILabel alloc] init];
//    label.textColor = [UIColor lightGrayColor];
//    label.font = [UIFont systemFontOfSize:12];
//    label.backgroundColor = [UIColor blackColor];
//    label.text = @"流行趋势";
//    [self.view addSubview:label];
//    
//    //用 masonry 设置label的位置
//    [label mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.size.mas_equalTo(CGSizeMake(300, 10));
//        
//        make.centerX.mas_equalTo(self.view.center);
//        make.top.equalTo(self.view).with.offset(74);
//        make.left.equalTo(self.view).with.offset(10);
//        make.right.equalTo(self.view).with.offset( -10);
//    }];
    
    __block __typeof(&*self)ws = self;
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = NO;
    self.headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 200)];
    [self.view addSubview:_headView];
    _tableView.tableHeaderView = _headView;
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(ws.view.mas_left).with.offset(0);
        make.right.equalTo(ws.view.mas_right).with.offset(0);
        make.top.equalTo(ws.view.mas_top).with.offset(0);
        make.bottom.equalTo(ws.view.mas_bottom).with.offset(0);
    }];
    [_tableView release];
}
- (NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 5;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_tableView registerClass:[WMETheFindTableViewCell class] forCellReuseIdentifier:@"findCell"];
    WMETheFindTableViewCell *findCell = [_tableView dequeueReusableCellWithIdentifier:@"findCell" forIndexPath:indexPath];
    if (_dataArr.count != 0) {
        if ([_dataArr[indexPath.row] count] == 4) {
            findCell.dataArr = _dataArr[indexPath.row];
            findCell.titleStr = _titleArr[indexPath.row];
            findCell.delegate = self;
        }
        //不能被点击
        findCell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return findCell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 130;
}
#pragma mark - 数据请求
-(void)data
{
    self.dataArr = [NSMutableArray array];
    self.titleArr = [NSMutableArray array];
    self.collectionArr = [NSMutableArray array];
    NSString *str = @"http://www.duitang.com/napi/index/groups/?app_code=gandalf&app_version=5.8%20rv%3A149591&device_name=iPhone%205&device_platform=iPhone5%2C2&locale=zh_CN&platform_name=iPhone%20OS&platform_version=9.2&screen_height=568&screen_width=320";
    AFHTTPSessionManager *data = [AFHTTPSessionManager manager];
    [data GET:str parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //        NSLog(@"%@", responseObject);
        
        NSMutableArray *arr = [NSMutableArray array];
        arr = responseObject[@"data"];
        self.collectionArr = arr[0][@"group_items"];
        for (NSInteger i = 1; i <= 5; i++){
            NSDictionary *tempDic = arr[i];
            NSString *tempStr = tempDic[@"group_name"];
            [self.titleArr addObject:tempStr];
            NSArray *temp = tempDic[@"group_items"];
            [self.dataArr addObject:temp];
        }
        [_tableView reloadData];
        [_collectionView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        nil;
    }];
    
}
#pragma mark - findPush的协议方法
- (void)findPushAction:(NSString *)str
{
    NSString *urlId = [str substringFromIndex:49];
    NSLog(@"%@", urlId);
    WMEFindContentViewController *findContent = [[WMEFindContentViewController alloc] init];
    findContent.interface = urlId;

    [self.navigationController pushViewController:findContent animated:YES];
    [findContent release];
}


- (void)createCollection
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = CGSizeMake(100, 120);

    layout.minimumLineSpacing = 20;
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 140) collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    //隐藏滚动条
    _collectionView.showsHorizontalScrollIndicator = NO;
    //边缘弹动
    _collectionView.bounces = NO;
    _collectionView.backgroundColor = [UIColor whiteColor];
    [self.headView addSubview:_collectionView];
    
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_headView.mas_left).with.offset(0);
        make.right.equalTo(_headView.mas_right).with.offset(0);
        make.top.equalTo(_headView.mas_top).with.offset(30);
        make.height.equalTo(@140);
    }];
    [_collectionView release];
}

#pragma mark- collectionView的协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _collectionArr.count - 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    [_collectionView registerClass:[WMEFindHeadCollectionViewCell class] forCellWithReuseIdentifier:@"findHeadCell"];
    WMEFindHeadCollectionViewCell *findHendCell = [_collectionView dequeueReusableCellWithReuseIdentifier:@"findHeadCell" forIndexPath:indexPath];
    if (_collectionArr.count != 0) {
        findHendCell.dic = _collectionArr[indexPath.item];
    }
    return findHendCell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = _collectionArr[indexPath.row];
    if(indexPath.row < 7) {
        NSString *tempStr = [dic[@"target"] substringWithRange:NSMakeRange(40, 33)];
        NSString *str = @"http://203.80.144.213/napi/theme/detail/?platform_version=4.4.4&device_platform=L36h&__dtac=%257B%2522_r%2522%253A%2520%2522666681%2522%257D&screen_width=1080&screen_height=1776&__domain=www.duitang.com&app_version=67&theme_id=554c8abaa310def67913c5c0&platform_name=Android&locale=zh&app_code=nayutas";
        NSString *url = [str stringByReplacingOccurrencesOfString:@"theme_id=554c8abaa310def67913c5c0" withString:tempStr];
        AFHTTPSessionManager *userData = [AFHTTPSessionManager manager];
        [userData GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            nil;
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            //        NSLog(@"%@", responseObject);
            NSMutableDictionary *myDic = responseObject[@"data"];
            WMEFindCollectionViewController *findCollectionVC = [[WMEFindCollectionViewController alloc] init];
            findCollectionVC.myDic = myDic;
            findCollectionVC.myStr = myDic[@"data_src"][@"filter_id"];
            [self.navigationController pushViewController:findCollectionVC animated:YES];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            nil;
        }];

    }
    
    
}
- (void)searchAction:(UIBarButtonItem *)btn
{
//    WMEFindSearchViewController *search = [[WMEFindSearchViewController alloc] init];
//    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:search];
//    [self presentViewController:navi animated:YES completion:^{
//        
//    }];
    SearchViewController *search = [[SearchViewController alloc] init];
    [self.navigationController pushViewController:search animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
